package cn.edu.scnu.user.service;

import cn.edu.scnu.pojo.User;
import cn.edu.scnu.vo.Card;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class RelationService {

    @Autowired
    private JedisCluster jedis;

    @Autowired
    private UserService userService;

    public List<Card> getLists(User user, String username, String type) {
        String key = username + ":" + type;
        Set<String> result = jedis.smembers(key);
        List<Card> data = new ArrayList<>();
        if (user == null) {
            for (String follow : result) {
                Map<String, String> info = userService.getInfoByUsername(follow);
                data.add(new Card(follow, info.get("nickname"), info.get("imgurl"), false));
            }
        } else if (username.equals(user.getUsername()) && type.equals("follows")) {
            for (String follow : result) {
                Map<String, String> info = userService.getInfoByUsername(follow);
                data.add(new Card(follow, info.get("nickname"), info.get("imgurl"), true));
            }
        } else {
            Set<String> follows = jedis.smembers(user.getUsername() + ":follows");
            for (String follow : result) {
                Card card = new Card();
                Map<String, String> info = userService.getInfoByUsername(follow);
                card.setUsername(follow);
                card.setImgurl(info.get("imgurl"));
                card.setNickname(info.get("nickname"));
                card.setLoginUserNameIsFollow(follows.contains(follow));
                data.add(card);
            }
        }
        return data;
    }

    public void follow(User user, String username) {
        if (jedis.sismember(user.getUsername() + ":follows", username)) {
            jedis.srem(user.getUsername() + ":follows", username);
            jedis.srem(username + ":fans", user.getUsername());
        } else {
            jedis.sadd(user.getUsername() + ":follows", username);
            jedis.sadd(username + ":fans", user.getUsername());
        }
    }
}
